package com.ruoyi.quartz.service.impl;

import com.ruoyi.common.constant.ScheduleConstants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.exception.job.TaskException;
import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.domain.SysJobDraft;
import com.ruoyi.quartz.domain.SysJobFetcher;
import com.ruoyi.quartz.domain.SysJobTable;
import com.ruoyi.quartz.domain.dto.SysJobListInput;
import com.ruoyi.quartz.domain.dto.SysJobRunOnceInput;
import com.ruoyi.quartz.domain.dto.SysJobSaveInput;
import com.ruoyi.quartz.domain.dto.SysJobUpdateInput;
import com.ruoyi.quartz.service.ISysJobService;
import com.ruoyi.quartz.util.ScheduleUtils;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.babyfish.jimmer.Page;
import org.babyfish.jimmer.sql.JSqlClient;
import org.babyfish.jimmer.sql.ast.mutation.SaveMode;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 定时任务调度信息 服务层
 *
 * @author ruoyi
 */
@Service
@RequiredArgsConstructor
public class SysJobServiceImpl implements ISysJobService {

    private final Scheduler scheduler;
    private final JSqlClient sqlClient;

    /**
     * 项目启动时，初始化定时器 主要是防止手动修改数据库导致未同步到定时任务处理（注：不能手动修改数据库ID和任务组名，否则会导致脏数据）
     */
    @PostConstruct
    public void init() throws SchedulerException, TaskException {
        scheduler.clear();
        SysJobTable table = SysJobTable.$;
        List<SysJob> jobList = sqlClient.createQuery(table)
                .select(table.fetch(SysJobFetcher.$.allScalarFields()))
                .execute();
        for (SysJob job : jobList) {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
    }

    /**
     * 获取quartz调度器的计划任务列表
     *
     * @param job 调度信息
     * @return
     */
    @Override
    public List<SysJob> selectJobList(SysJobListInput job) {
        SysJobTable table = SysJobTable.$;
        return sqlClient.createQuery(table)
                .where(
                        table.jobGroup().eqIf(job.getJobGroup()),
                        table.jobName().ilikeIf(job.getJobName()),
                        table.status().eqIf(job.getStatus())
                )
                .select(table.fetch(SysJobFetcher.$.allScalarFields()))
                .execute();
    }

    /**
     * 通过调度任务ID查询调度信息
     *
     * @param jobId 调度任务ID
     * @return 调度任务对象信息
     */
    @Override
    public SysJob selectJobById(String jobId) {
        return sqlClient.findById(SysJob.class, jobId);
    }

    /**
     * 暂停任务
     *
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int pauseJob(SysJob job) throws SchedulerException {
        String jobId = job.jobId();
        String jobGroup = job.jobGroup();
        SysJobTable table = SysJobTable.$;
        int rows = sqlClient.createUpdate(table)
                .set(table.status(), ScheduleConstants.Status.PAUSE.getValue())
                .where(table.jobId().eq(jobId))
                .execute();
        if (rows > 0) {
            scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 恢复任务
     *
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int resumeJob(SysJob job) throws SchedulerException {
        SysJobTable table = SysJobTable.$;
        String jobId = job.jobId();
        String jobGroup = job.jobGroup();
        int rows = sqlClient.createUpdate(table)
                .set(table.status(), ScheduleConstants.Status.NORMAL.getValue())
                .where(table.jobId().eq(jobId))
                .execute();
        if (rows > 0) {
            scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 删除任务后，所对应的trigger也将被删除
     *
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteJob(SysJob job) throws SchedulerException {
        String jobId = job.jobId();
        String jobGroup = job.jobGroup();
        int rows = sqlClient.deleteById(SysJob.class, jobId).getTotalAffectedRowCount();
        if (rows > 0) {
            scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 批量删除调度信息
     *
     * @param jobIds 需要删除的任务ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteJobByIds(String[] jobIds) throws SchedulerException {
        for (String jobId : jobIds) {
            SysJob job = selectJobById(jobId);
            deleteJob(job);
        }
    }

    /**
     * 任务调度状态修改
     *
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int changeStatus(SysJob job) throws SchedulerException {
        int rows = 0;
        String status = job.status();
        if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) {
            rows = resumeJob(job);
        } else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) {
            rows = pauseJob(job);
        }
        return rows;
    }

    /**
     * 立即运行任务
     *
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean run(SysJobRunOnceInput job) throws SchedulerException {
        boolean result = false;
        String jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        SysJob properties = selectJobById(job.getJobId());
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties);
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey)) {
            result = true;
            scheduler.triggerJob(jobKey, dataMap);
        }
        return result;
    }

    /**
     * 新增任务
     *
     * @param job 调度信息 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertJob(SysJobSaveInput job) throws SchedulerException, TaskException {
        SysJob sysJob = SysJobDraft.$.produce(job.toEntity(),
                draft -> draft.setStatus(ScheduleConstants.Status.PAUSE.getValue()));
        int rows = sqlClient.saveCommand(sysJob)
                .setMode(SaveMode.INSERT_ONLY)
                .execute().getTotalAffectedRowCount();
        if (rows > 0) {
            ScheduleUtils.createScheduleJob(scheduler, sysJob);
        }
        return rows;
    }

    /**
     * 更新任务的时间表达式
     *
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateJob(SysJobUpdateInput job) throws SchedulerException, TaskException {
        SysJob properties = sqlClient.findById(SysJob.class, job.getJobId());
        int rows = sqlClient.saveCommand(job)
                .setMode(SaveMode.UPDATE_ONLY)
                .execute().getTotalAffectedRowCount();
        if (rows > 0) {
            updateSchedulerJob(job, properties.jobGroup());
        }
        return rows;
    }

    @Override
    public Page<SysJob> selectJobPage(SysJobListInput job, PageQuery pageQuery) {
        SysJobTable table = SysJobTable.$;
        return sqlClient.createQuery(table)
                .where(
                        table.jobGroup().eqIf(job.getJobGroup()),
                        table.jobName().ilikeIf(job.getJobName()),
                        table.status().eqIf(job.getStatus())
                )
                .select(table.fetch(SysJobFetcher.$.allScalarFields()))
                .fetchPage(pageQuery.getPageNum(), pageQuery.getPageSize());
    }

    /**
     * 更新任务
     *
     * @param job      任务对象
     * @param jobGroup 任务组名
     */
    public void updateSchedulerJob(SysJobUpdateInput job, String jobGroup) throws SchedulerException, TaskException {
        String jobId = job.getJobId();
        // 判断是否存在
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey)) {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(jobKey);
        }
        ScheduleUtils.createScheduleJob(scheduler, job.toEntity());
    }

    /**
     * 校验cron表达式是否有效
     *
     * @param cronExpression 表达式
     * @return 结果
     *//*
    @Override
    public boolean checkCronExpressionIsValid(String cronExpression) {
        return CronUtils.isValid(cronExpression);
    }*/
}
